/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.execution;

import com.softwarecraftsmen.orogeny.BuildScript;
import com.softwarecraftsmen.orogeny.TasksExecuteInParallel;
import org.jetbrains.annotations.NotNull;

import static java.lang.management.ManagementFactory.getOperatingSystemMXBean;
import static java.lang.management.ManagementFactory.getRuntimeMXBean;
import java.util.concurrent.ExecutorService;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.Executors.newSingleThreadExecutor;

public class TasksExecuteInParallelProcessor
{
	private final boolean useASingleThread;

	public TasksExecuteInParallelProcessor(final @NotNull Class<? extends BuildScript> buildScript)
	{
		final TasksExecuteInParallel tasksExecuteInParallel = buildScript.getAnnotation(TasksExecuteInParallel.class);
		useASingleThread = (tasksExecuteInParallel == null) || !tasksExecuteInParallel.value();
	}

	@NotNull
	public ExecutorService taskThreadPool()
	{
		if (useASingleThread)
		{
			return newSingleThreadExecutor();
		}
		return newFixedThreadPool(getOperatingSystemMXBean().getAvailableProcessors());
	}

	public boolean isSingleThreaded()
	{
		return useASingleThread;
	}
}